var express = require('express');
var app = express();
// var http = require('http').createServer(app).listen(1400);
var xx = app.listen(1400);
var io = require('socket.io').listen(xx);



// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {
	console.log("Connection");
	// when the client emits 'sendchat', this listens and executes
	socket.on('sendchat', function (data) {
		// we tell the client to execute 'updatechat' with 2 parameters
		io.sockets.emit('updatechat', socket.username, data);
	});
	socket.on('cm_background', function(data) {
	console.log("======================================================================");
		console.log("cm_background "+data.imageUrl+" id "+data.pageId);
			socket.broadcast.to(socket.room).emit('sm_background', {
				id: data.id,
				roomId: data.roomid,
				pageId: data.pageId,
				imageUrl: data.imageUrl,
			});
		});
	// when the client emits 'adduser', this listens and executes
	socket.on('adduser', function(username){
		console.log("user added"+username);
		// we store the username in the socket session for this client
		socket.username = username;
		// add the client's username to the global list
		usernames[username] = username;
		// echo to client they've connected
		socket.emit('updatechat', 'SERVER', 'you have connected');
		// echo globally (all clients) that a person has connected
		socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
		// update the list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
	});

	// when the user disconnects.. perform this
	socket.on('disconnect', function(){
		// remove the username from global usernames list
		delete usernames[socket.username];
		// update list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
		// echo globally that this client has left
		socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
	});
});